package com.lysj.bhp.scheduled.job;


import com.lysj.bhp.scheduled.base.ScheduledContent;
import com.lysj.bhp.scheduled.domain.BhpcWallet;
import com.lysj.bhp.scheduled.domain.RechargeRecord;
import com.lysj.bhp.scheduled.domain.User;
import com.lysj.bhp.scheduled.util.EtherScanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

@Component
public class BhpcJob extends ScheduledContent {

    private static Logger logger = LoggerFactory.getLogger(BhpcJob.class);


    /*第一次10秒后执行，当执行完后0.2秒再执行，保证一秒并发不超过5个*/
    @Scheduled(initialDelay = 10000, fixedDelay = 500)
    public void queryBhpcWallet() {
        logger.info("BhpcJob is Starting ...");
        BhpcWallet bhpcWallet = bhpcWalletRepository.findFirstByOrderByLastQueryTimeAsc();
        if (bhpcWallet == null) {
            return;
        }
       double realBhpcBalance = EtherScanUtil.getBalanceTokenBHPC("0x" + bhpcWallet.getAddress());//查询bhpc钱包的可用余额
        if (realBhpcBalance < 0) { //
            logger.error("EherscanUtil return -1,bhpcWalletId is " + bhpcWallet.getBhpcWalletId());
            bhpcWallet.setLastQueryTime(System.currentTimeMillis());
            bhpcWalletRepository.save(bhpcWallet); // !!!即使发生错误,也应该继续执行下一次的查询!!!
            return;
        }
        if (BigDecimal.valueOf(realBhpcBalance).compareTo(bhpcWallet.getBookKeepBalance()) == 1) { //查询到的余额大于钱包得真实余额(记账余额)，则更新
            logger.info("BhpcWallet BHPC Balance Increment,Start Record!" + bhpcWallet.getBhpcWalletId());
            BigDecimal increase = BigDecimal.valueOf(realBhpcBalance).subtract(bhpcWallet.getBookKeepBalance()); // 增加的余额
            bhpcWallet.setBalance(bhpcWallet.getBalance().add(increase));//更新钱包的总额
            bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().add(increase));//更新钱包的可用余额
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(100);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(bhpcWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecord.setAuthentication("成功");
            rechargeRecord.setName("BHPC");
            rechargeRecord.setChineseName("算力现金");
            rechargeRecord.setAddress("0x" + bhpcWallet.getAddress());
            rechargeRecordRepository.save(rechargeRecord);
        }
        bhpcWallet.setBookKeepBalance(BigDecimal.valueOf(realBhpcBalance));//更新钱包的记账余额
        bhpcWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        bhpcWalletRepository.save(bhpcWallet);

    }

}
